﻿#include <QApplication>
#include <QWidget>

//在Windows平台去掉黑窗口：
#pragma comment(linker,"/subSystem:console /entry:mainCRTStartup")
//如果想让黑窗口出来，就把Windows 改成 console

#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>


class Server : public QObject
{

private:
	QTcpServer* m_server;

public:
	Server(QObject* parent = nullptr)
		:QObject(parent)
		, m_server(new QTcpServer)
	{

		//1.监听：
		if (!m_server->listen(QHostAddress::Any, 56789))
		{
			qWarning() << "listen failed>" << m_server->errorString();
		}

		//2.接受新的连接：
		connect(m_server, &QTcpServer::newConnection, this, &Server::onNewConnection);
	
	
	
	}


	//判断有没有新的连接：
	void onNewConnection()
	{
		while (m_server->hasPendingConnections())
		{
			qInfo() << "有新的连接";
			//1.获取新的连接：返回客户端的socket：
			auto sock = m_server->nextPendingConnection();

			//2.连接客户端的sock的信号：
			connect(sock, &QTcpSocket::readyRead, this, &Server::onClientReadyRead);
		}
	}

	void onClientReadyRead()
	{
		auto sock = dynamic_cast<QTcpSocket*> (sender());
		if (!sock)
			return;

		while (sock->bytesAvailable())
		{
			qInfo() << sock->readAll();
		}

	}
};



int main(int argc, char* argv[])
{
	QApplication a(argc, argv);
	Server w;

	return a.exec();
}

